package com.goldcn.user.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.model.DataResult;
import com.goldcn.common.util.CommonUtils;
import com.goldcn.common.util.IdGen;
import com.goldcn.config.ProConstants;
import com.goldcn.enums.TopDeptEnum;
import com.goldcn.interceptor.SystemContext;
import com.goldcn.user.ErpDto.ResultData;
import com.goldcn.user.dao.CountMapper;
import com.goldcn.user.dao.OrganizationalMapper;
import com.goldcn.user.dao.UserInfoMapper;
import com.goldcn.user.dto.UserCountDto;
import com.goldcn.user.dto.UserQtyCountDto;
import com.goldcn.user.model.Count;
import com.goldcn.user.model.Organizational;
import com.goldcn.user.model.UserInfo;
import com.goldcn.user.vo.*;
import com.goldcn.util.HttpUtil;
import com.google.common.primitives.Longs;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by 1111 on 2016/12/8.
 */
@Service
@Transactional
public class CountService {
    @Autowired
    CountMapper countMapper;

    @Autowired
    OrganizationalService organizationalService;

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    OrganizationalMapper organizationalMapper;

    @Autowired
    CompanyInfoService companyInfoService;

    @Autowired
    RestTemplate restTemplate;

    public Object addCount(Count count){
        count.setId(IdGen.get().nextId());
        count.setMemberCount(0);
        count.setSalesCount(0);
        count.setUpdateTime(CommonUtils.getCurTimestamp());
        count.setCompanyID(SystemContext.getCompanyID());
        countMapper.insertSelective(count);
        return "success";
    }

    public Object initMember(Long companyID){
        Count count1 = new Count();
        count1.setId(companyID);
        count1.setMemberCount(0);
        count1.setSalesCount(0);
        count1.setUpdateTime(CommonUtils.getCurTimestamp());
        count1.setCompanyID(companyID);
        countMapper.insertSelective(count1);
        Count count2 = new Count();
        count2.setId(Long.parseLong(companyID.toString().substring(0,companyID.toString().length()-1)));
        count2.setMemberCount(0);
        count2.setSalesCount(0);
        count2.setUpdateTime(CommonUtils.getCurTimestamp());
        count2.setCompanyID(companyID);
        countMapper.insertSelective(count2);
        return "success";
    }

    public Object delteCountByOID(Map<String,Object> params){
        countMapper.deleteByOID(params);
        return "success";
    }

    /**
     * 会员、顾问数量每日更新统计
     * @param startTime
     * @param endTime
     * @return
     */

    public Object updateCount(Long startTime,Long endTime){
        ResultData<List<Map<String, Object>>> result = null;
        try {
            result = restTemplate.getForObject(ProConstants.getAllCompany,ResultData.class) ;
        }catch (Exception e){
            throw new ServiceException("获取全部公司信息失败");
        }

        List<Map<String, Object>> sysConfigs = result.getData();
        for (Map<String, Object> m : sysConfigs) {
            String companyInfoID =  m.get("companyInfoID").toString();
            updateCountByCompanyID(startTime, endTime, Long.parseLong(companyInfoID));
        }
        return "success";


    }

    private String updateCountByCompanyID(Long startTime, Long endTime, Long companyID) {
        Integer type; //用于判断是手工还是自动
        if(startTime==null || endTime==null){
            startTime  = getTimesamp(1);
            endTime  = getTimesamp(2);
            type =1;
        }else {
            type = 2;
        }
        List<Count> countList = countMapper.selectAll(companyID);
        if(countList==null || countList.size()==0){
            return "";
        }
        Long updateTime = countList.get(0).getUpdateTime();

        switch (type){
            case 1:   //自动更新则需要判断是否已经更新过
                if(updateTime>getTimesamp(2)){  //如果大于今天零点
                    throw new ServiceException("今天统计已经更新",RestConst.ErrorCode.FORM_FAIL);
                }
                break;
            case 2:   //手动更新则打印下日记
                System.out.print("手动更新了该时间段的统计:"+startTime+"--"+endTime);
                break;
        }

        for(Count count : countList) {
            UserQtyCountDto userQtyCountDto = new UserQtyCountDto();
            userQtyCountDto.setCompanyID(companyID);
            //统计销售经理的的数据
            if (count.getSalesManagerID() != 0) {

                List<Long> paterIDList = new ArrayList<>();
                List<Integer> typeList = new ArrayList<>();
                typeList.add(3);
                //统计顾问则是 updateTime
                userQtyCountDto.setuStartTime(startTime);
                userQtyCountDto.setuEndTime(endTime);

                paterIDList.add(count.getSalesManagerID());
                userQtyCountDto.setTypeList(typeList);
                userQtyCountDto.setPaterIDList(paterIDList);
                int consultantQty = userInfoMapper.selectUserQtyByCondition(userQtyCountDto);


                List<Long> paterIDList1  = userInfoMapper.selectConsultantIDByManagerID(count.getSalesManagerID()); //获取销售经理下所有销售顾问
                if(paterIDList1 == null){
                    paterIDList1 = new ArrayList<>();
                }
                paterIDList1.add(count.getSalesManagerID());
                userQtyCountDto.setPaterIDList(paterIDList1);
                typeList.clear();
                typeList.add(4);

                //统计会员则是 addTime
                userQtyCountDto.setuStartTime(null);
                userQtyCountDto.setuEndTime(null);
                userQtyCountDto.setStartTime(startTime);
                userQtyCountDto.setEndTime(endTime);

                userQtyCountDto.setTypeList(typeList);
                int userQty = userInfoMapper.selectUserQtyByCondition(userQtyCountDto);

                count.setMemberCount(count.getMemberCount()+userQty);
                count.setSalesCount(count.getSalesCount()+consultantQty);
                count.setUpdateTime(CommonUtils.getCurTimestamp());
                countMapper.updateByPrimaryKeySelective(count);
            } else { //统计银行数据
                if ((count.getId()+"").equals(companyID+"")) {  //统计所有数量
                }
                if ((count.getId()+"").equals(companyID.toString().substring(0,companyID.toString().length()-1))) {  //单独统计总行数据
                    Long organizationalID = organizationalService.selectHeadCCB(companyID).getoID();
                    userQtyCountDto.setOrganizationalID(organizationalID);
                }
                //单独统计分行数据
                if (count.getBranchID() != 0 && count.getTwoLevelBranchID() == 0 && count.getSubbranchID() == 0 && count.getSalesManagerID() == 0) {
                    userQtyCountDto.setOrganizationalID(count.getBranchID());
                }
                //单独统计二级分行数据
                if (count.getTwoLevelBranchID() != 0 && count.getSubbranchID() == 0 && count.getSalesManagerID() == 0) {
                    userQtyCountDto.setOrganizationalID(count.getTwoLevelBranchID());
                }
                //单独统计支行数据
                if (count.getSubbranchID() != 0 && count.getSalesManagerID() == 0) {
                    userQtyCountDto.setOrganizationalID(count.getSubbranchID());
                }

                //顾问数量
                List<Integer> typeList = new ArrayList<>();
                typeList.add(3);
                //统计顾问则是 updateTime
                userQtyCountDto.setuStartTime(startTime);
                userQtyCountDto.setuEndTime(endTime);

                userQtyCountDto.setTypeList(typeList);
                int consultantQty = userInfoMapper.selectUserQtyByCondition(userQtyCountDto);

                //会员数量
                typeList.clear();
                typeList.add(4);
                //统计会员则是 addTime
                userQtyCountDto.setuStartTime(null);
                userQtyCountDto.setuEndTime(null);
                userQtyCountDto.setStartTime(startTime);
                userQtyCountDto.setEndTime(endTime);

                userQtyCountDto.setTypeList(typeList);
                int userQty = userInfoMapper.selectUserQtyByCondition(userQtyCountDto);

                count.setMemberCount(count.getMemberCount()+userQty);
                count.setSalesCount(count.getSalesCount()+consultantQty);
                count.setUpdateTime(CommonUtils.getCurTimestamp());
                countMapper.updateByPrimaryKeySelective(count);
            }
        }
        return "success";

    }

    /**
     * 查询实时用户总数
     * @param userID
     * @param organizationalID
     * @return
     */
    public Object selectUserStatCount(Long userID,Long organizationalID){
        Map<String,Object> map = new HashMap<>();
        Organizational organizational = organizationalMapper.selectByPrimaryKey(organizationalID);
        map.put("companyID", organizational.getCompanyID());
        if(userID!=0){
            map.put("userID",userID);
        }
        if(organizationalID!=0){
            map.put("organizationalID",organizationalID);
            List<Long> list = new ArrayList<>();
            Map<String, Object> params = new HashMap<>();
            switch (organizational.getLevel()) {

                case 2:
                    params.put("branchID", organizationalID);
                    list = organizationalMapper.selectSubOIDList(params);
                    list.add(organizationalID);
                    break;
                case 3:
                    params.put("twoLevelBranchID",organizationalID);
                    list = organizationalMapper.selectSubOIDList(params);
                    list.add(organizationalID);
                    break;
                case 4:
                    list.add(organizationalID);
                    break;
            }
            map.put("list",list);
        }

        Map<String,BigDecimal> user= userInfoMapper.selectUserStatCount(map);
        Count count = new Count();
        if(user!=null && user.containsKey("memberCount")){
            count.setMemberCount(user.get("memberCount").intValue());
        }else {
            count.setMemberCount(0);
        }
        if(user!=null && user.containsKey("salesCount")){
            count.setSalesCount(user.get("salesCount").intValue());

        }else {
            count.setSalesCount(0);
        }
        if(user!=null && user.containsKey("salesManagerCount")){
            count.setSalesManagerID(user.get("salesManagerCount").longValue());
        }else {
            count.setSalesManagerID(0L);

        }

        return count;
    }

    //查询内部员工userID的个人及其组织信息用于统计[type:1仅查询用户信息，2包括用户的基本统计信息]
    public Object selectForOrderCount(Long userID,int type)throws Exception{
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userID);
        Organizational organizational = organizationalMapper.selectByPrimaryKey(userInfo.getOrganizationalID());
        UserOrganizationalInfoVo infoVo = new UserOrganizationalInfoVo();
        infoVo.setOrganizationalID(userInfo.getOrganizationalID());
        infoVo.setOrganizationalName(organizational.getOrganizationalName());
        infoVo.setLevel(organizational.getLevel());
        //infoVo.setType(userInfo.getType());
        infoVo.setType(Objects.equals(userInfo.getIsAdmin(),1)?1:userInfo.getType());
        if(type==2){
            UserAndCountVo userAndCountVo = new UserAndCountVo();
            BeanUtils.copyProperties(userAndCountVo,infoVo);
            if(infoVo.getType()==1){ //管理员
                //待审核的员工数量
                //总部可以查看所有start
                //TODO 总部或超级管理员可以查看
                TopDeptEnum topDeptEnum = TopDeptEnum.valuekOf(SystemContext.getCompanyID());
                Long deptID = topDeptEnum.getDeptID();
                if(com.google.common.base.Objects.equal(deptID,infoVo.getOrganizationalID())){//总部
                    infoVo.setOrganizationalID(null);
                }
                //总部可以查看所有end
                infoVo.setCompanyID(SystemContext.getCompanyID());
                Integer employeeIsAuditQty = userInfoMapper.selectQtyByEmployeeIsAudit(infoVo);
                infoVo.setOrganizationalID(userAndCountVo.getOrganizationalID());
                userAndCountVo.setEmployeeIsAuditQty(employeeIsAuditQty==null?0:employeeIsAuditQty);
                if(infoVo.getLevel()==1){
                    userAndCountVo.setCompanyQty(companyInfoService.selectCompanyQtyByIsAudit(1,userInfo.getCompanyID()));//审核通过的供应商数量
                    userAndCountVo.setCompanyIsAuditQty(companyInfoService.selectCompanyQtyByIsAudit(0,userInfo.getCompanyID()));//待审核的供应商数量

//                    Count count =  selectByPrimaryKey((long)0);  //id为0则统计所有会员、顾问数据
                    Count count = selectByPrimaryKey(SystemContext.getCompanyID());
                    userAndCountVo.setVipUserQty(count.getMemberCount()+count.getSalesCount());
                    userAndCountVo.setConsultantUserQty(count.getSalesCount());
                }else {   //统计该行及其所有下属银行的统计数据
                    UserCountDto userCountDto = new UserCountDto();
                    switch (infoVo.getLevel()) {
                        case 2: //分行
                            userCountDto.setBranchID(infoVo.getOrganizationalID());
                            break;
                        case 3://二级分行
                            userCountDto.setTwoLevelBranchID(infoVo.getOrganizationalID());
                            break;
                        case 4://支行
                            userCountDto.setSubbranchID(infoVo.getOrganizationalID());
                            break;
                    }
                    userCountDto.setSalesManagerID((long)0);
                    CountVo countVo = new CountVo();
                    Object object = countMapper.selectCountByConditon(userCountDto);
                    if(object != null){
                        countVo = (CountVo)object;
                    }
                    int memberCount = countVo.getMemberCount()==null ? 0 : countVo.getMemberCount();
                    int salesCount = countVo.getSalesCount()==null ? 0 : countVo.getSalesCount();
                    userAndCountVo.setVipUserQty(memberCount+salesCount);
                    userAndCountVo.setConsultantUserQty(salesCount);
                }
            }else if(infoVo.getType()==2){  //销售经理
                userAndCountVo.setUserIsAuditQty(userInfoService.selectUserApplyIsAuditQty(userID));  //该销售经理下的销售顾问申请数量
                UserCountDto userCountDto = new UserCountDto();
                userCountDto.setSalesManagerID(userID);
                CountVo countVo = new CountVo();
                Object object = countMapper.selectCountByConditon(userCountDto);
                if(object != null){
                    countVo = (CountVo)object;
                }
                int memberCount = countVo.getMemberCount()==null ? 0 : countVo.getMemberCount();
                int salesCount = countVo.getSalesCount()==null ? 0 : countVo.getSalesCount();
                userAndCountVo.setVipUserQty(memberCount+salesCount);
                userAndCountVo.setConsultantUserQty(salesCount);
            }
            return userAndCountVo;
        }else {
            return infoVo;
        }
    }

    //下属部门会员数据统计
    public PageInfo selectCountByDepartment(Long userID,int pageNum,int pageSize)throws Exception{
        UserOrganizationalInfoVo infoVo = (UserOrganizationalInfoVo)selectForOrderCount(userID,1);

        PageHelper.startPage(pageNum,pageSize);
        List<UserCountVo> userCountVoList = new ArrayList<>();
        List<Long> oOrUserIDList = new ArrayList<>();  //用于查询交易额
        int type=0; //用于查询交易额

        Map<String,Object> params = new HashMap<>();
        if(infoVo.getType()==1){  //管理员
            if(infoVo.getLevel()==4){ //支行统计下属销售经理的会员数
                type=4;
                params.put("subbranchID",infoVo.getOrganizationalID());
                userCountVoList = countMapper.selectGroupBySalesManagerID(params);
                if(userCountVoList.size()>0){
                    for(UserCountVo userCountVo : userCountVoList){
                        userCountVo.setoOrUserName(userInfoService.selectByUserID(userCountVo.getoOrUserID()).getName());
                        userCountVo.setUserQty(userCountVo.getUserQty()==null ? 0 : userCountVo.getUserQty());
                        oOrUserIDList.add(userCountVo.getoOrUserID());
                    }
                }

            }else { //统计下属部门的会员数
                switch (infoVo.getLevel()) {
                    case 1:
                        userCountVoList = countMapper.selectGroupByBranchID(null);
                        type=1;
                        break;
                    case 2:
                        type=2;
                        params.put("branchID",infoVo.getOrganizationalID());
                        userCountVoList = countMapper.selectGroupByTwoLevelBranchID(params);
                        break;
                    case 3:
                        type=3;
                        params.put("twoLevelBranchID",infoVo.getOrganizationalID());
                        userCountVoList = countMapper.selectGroupBySubbranchID(params);
                        break;
                }
                if(userCountVoList.size()>0){
                    for(UserCountVo userCountVo : userCountVoList){
                        userCountVo.setoOrUserName(organizationalService.selectByOID(userCountVo.getoOrUserID()).getOrganizationalName());
                        userCountVo.setUserQty(userCountVo.getUserQty()==null ? 0 : userCountVo.getUserQty());
                        oOrUserIDList.add(userCountVo.getoOrUserID());
                    }
                }
            }
        }else if(infoVo.getType()==2){  //销售经理下的顾问会员数统计
            type=5;
            List<Long> paterIDList = userInfoMapper.selectConsultantIDByManagerID(userID);
            if(paterIDList.size()>0) {
                List<UserCountVo> ucvList = userInfoMapper.selectUserQtyByPaterID(paterIDList);
                for(Long paterID : paterIDList){
                    UserCountVo userCountVo = new UserCountVo();
                    userCountVo.setoOrUserID(paterID);
                    userCountVo.setUserQty(0);
                    userCountVo.setoOrUserName(userInfoService.selectByUserID(userCountVo.getoOrUserID()).getName());
                    if(ucvList.size()>0){   //如果存在数据则比对赋值
                        for(UserCountVo ucv : ucvList){
                            if(ucv.getoOrUserID().equals(paterID)){
                                userCountVo.setUserQty(ucv.getUserQty());
                            }
                        }
                    }
                    userCountVoList.add(userCountVo);
                    oOrUserIDList.add(paterID);
                }
            }
        }

        if(oOrUserIDList.size()>0) {  //获取销售额
            Map<String,Object> param = getTransactionByOzOrUserIDList(oOrUserIDList, type);
            for(UserCountVo userCountVo : userCountVoList){
                userCountVo.setTransanctionTotal(BigDecimal.ZERO);  //默认给0
                userCountVo.setAverageTransanctionTotal(BigDecimal.ZERO); //同上
                BigDecimal total = param.get(userCountVo.getoOrUserID().toString())==null ? BigDecimal.ZERO : new BigDecimal(param.get(userCountVo.getoOrUserID().toString()).toString());
                userCountVo.setTransanctionTotal(total);
                if(userCountVo.getUserQty()==0){
                    userCountVo.setAverageTransanctionTotal(userCountVo.getTransanctionTotal());
                }else {
                    userCountVo.setAverageTransanctionTotal(userCountVo.getTransanctionTotal().divide(new BigDecimal(userCountVo.getUserQty()),3,BigDecimal.ROUND_HALF_UP));
                }
            }
        }
        PageInfo<UserCountVo> page = new PageInfo(userCountVoList);
        return page;
    }

    /**
     * 会员数量增长趋势统计，返回七个时间点
     * @param userID
     * @param timeType 1最近一月 2最近三月 3最近一年
     * @return
     */
    public Object getUserQtyTred(Long userID,int timeType)throws Exception{
        UserOrganizationalInfoVo infoVo = (UserOrganizationalInfoVo)selectForOrderCount(userID,1);
        UserQtyCountDto userQtyCountDto = new UserQtyCountDto();
        userQtyCountDto.setEndTime(getTimesamp(2)-1);  //昨天最后时刻
        userQtyCountDto.setCompanyID(SystemContext.getCompanyID());
        switch (timeType){
            case 1:
                userQtyCountDto.setStartTime(getTimesamp(4));
                break;
            case 2:
                userQtyCountDto.setStartTime(getTimesamp(5));
                break;
            case 3:
                userQtyCountDto.setStartTime(getTimesamp(6));
                break;
            default:throw new ServiceException("时间参数传入错误",RestConst.ErrorCode.FORM_FAIL);
        }

        Map<Long,Integer> tredParam = new LinkedHashMap<>();
        if(infoVo.getType()==1){  //管理员统计部门下的数据
            userQtyCountDto.setOrganizationalID(infoVo.getOrganizationalID());
            List<Integer> typeList = new ArrayList<>();
            typeList.add(3);
            typeList.add(4);
            userQtyCountDto.setTypeList(typeList);
            Map<Integer,Long> timesampInterval = getTimesampInterval(userQtyCountDto.getStartTime(),userQtyCountDto.getEndTime());

            for(int i=1;i<8;i++){
                userQtyCountDto.setStartTime(timesampInterval.get(i));
                userQtyCountDto.setEndTime(timesampInterval.get(i+1));
                int userQty = userInfoMapper.selectUserQtyByCondition(userQtyCountDto);
                tredParam.put(timesampInterval.get(i+1),userQty);
            }
        }
        if(infoVo.getType()==2){  //销售经理统计自己下的数据
            List<Long> paterIDList = userInfoMapper.selectConsultantIDByManagerID(userID);
            paterIDList.add(userID);  //用于查询下属所有会员
            List<Long> managerPaterIDList = new ArrayList<>();
            managerPaterIDList.add(userID); //用于查询下属销售顾问

            Map<Integer,Long> timesampInterval = getTimesampInterval(userQtyCountDto.getStartTime(),userQtyCountDto.getEndTime());

            for(int i=1;i<8;i++){
                List<Integer> typeList = new ArrayList<>();
                typeList.add(3);

                userQtyCountDto.setTypeList(typeList);
                userQtyCountDto.setPaterIDList(managerPaterIDList);
                userQtyCountDto.setStartTime(timesampInterval.get(i));
                userQtyCountDto.setEndTime(timesampInterval.get(i+1));
                int consultantQty = userInfoMapper.selectUserQtyByCondition(userQtyCountDto);

                typeList.clear();
                typeList.add(4);
                userQtyCountDto.setTypeList(typeList);
                userQtyCountDto.setPaterIDList(paterIDList);
                int userQty = userInfoMapper.selectUserQtyByCondition(userQtyCountDto);

                tredParam.put(timesampInterval.get(i+1),consultantQty+userQty);
            }
        }
        return tredParam;
    }

    /**
     * 根据List<oIDOrUserID>,type 来查询对应的name，会员、顾问数；订单统计需求
     * @param oOrUserIDList
     * @param type  1分行ID，2二级分行ID，3支行ID，4销售经理ID，5销售顾问ID
     * @return
     */
    public Object getUserQtyByList(List<Long> oOrUserIDList,int type){
        List<UserCountVo> countVoList = new ArrayList<>();
        Map<String,Object> params = new HashMap<>();
        params.put("list",oOrUserIDList);
        switch (type){
            case 1:
//                Count count = countMapper.selectByPrimaryKey(1l);
                Count count = countMapper.selectByPrimaryKey(Longs.tryParse(SystemContext.getCompanyID().toString().substring(0,SystemContext.getCompanyID().toString().length()-1)));
                UserCountVo ucvv = new UserCountVo();
                ucvv.setoOrUserID(1l);
                ucvv.setMemberCount(count.getMemberCount());
                ucvv.setSalesCount(count.getSalesCount());
                ucvv.setUserQty(count.getMemberCount()+count.getSalesCount());
                countVoList = countMapper.selectGroupByBranchID(params);
                countVoList.add(ucvv);
                break;
            case 2:
                countVoList = countMapper.selectGroupByTwoLevelBranchID(params);
                break;
            case 3:
                countVoList = countMapper.selectGroupBySubbranchID(params);
                break;
            case 4:
                countVoList = countMapper.selectGroupBySalesManagerID(params);
                break;
            case 5:
                List<UserCountVo> ucvList = userInfoMapper.selectUserQtyByPaterID(oOrUserIDList);
                for(Long paterID : oOrUserIDList){
                    UserCountVo userCountVo = new UserCountVo();
                    userCountVo.setoOrUserID(paterID);
                    userCountVo.setUserQty(0);
                    if(ucvList.size()>0){   //如果存在数据则比对赋值
                        for(UserCountVo ucv : ucvList){
                            if(ucv.getoOrUserID().equals(paterID)){
                                userCountVo.setUserQty(ucv.getUserQty());
                            }
                        }
                    }
                    countVoList.add(userCountVo);
                }
                break;
        }
        List<UserOnlyQtyVo> onlyQtyVoList = new ArrayList<>();
        if(countVoList.size()>0){
            for(UserCountVo countVo : countVoList){
                UserOnlyQtyVo userOnlyQtyVo = new UserOnlyQtyVo();
                if(type==4 || type==5){
                    countVo.setoOrUserName(userInfoService.selectByUserID(countVo.getoOrUserID()).getName());
                }else {
                    if(countVo.getoOrUserID()==1){
                        countVo.setoOrUserName("总部");
                    }else {
                        countVo.setoOrUserName(organizationalService.selectByOID(countVo.getoOrUserID()).getOrganizationalName());
                    }
                }
                userOnlyQtyVo.setUserQty(countVo.getUserQty());
                userOnlyQtyVo.setSalesCount(countVo.getSalesCount());
                userOnlyQtyVo.setMemberCount(countVo.getMemberCount());
                userOnlyQtyVo.setoOrUserName(countVo.getoOrUserName());
                userOnlyQtyVo.setoOrUserID(countVo.getoOrUserID());
                onlyQtyVoList.add(userOnlyQtyVo);
            }
        }
        return onlyQtyVoList;
    }

    //仅仅查询本部会员数量等统计数据
    public Object getSelfInfo(Long userID)throws Exception{
        UserOrganizationalInfoVo infoVo = (UserOrganizationalInfoVo) selectForOrderCount(userID,1);
        UserCountVo ucvv = new UserCountVo();
        int type=1;
        if(infoVo.getLevel()==1){
//            Count count = countMapper.selectByPrimaryKey(1l);
            Count count = countMapper.selectByPrimaryKey(Longs.tryParse(SystemContext.getCompanyID().toString().substring(0,SystemContext.getCompanyID().toString().length()-1)));
            ucvv.setoOrUserID(1l);
            ucvv.setoOrUserName("总部");
            ucvv.setMemberCount(count.getMemberCount());
            ucvv.setSalesCount(count.getSalesCount());
            ucvv.setUserQty(count.getMemberCount()+count.getSalesCount());
        }else {
            UserCountDto userCountDto = new UserCountDto();
            switch (infoVo.getLevel()){
                case 2:
                    userCountDto.setBranchID(infoVo.getOrganizationalID());
                    userCountDto.setTwoLevelBranchID(0l);
                    userCountDto.setSubbranchID(0l);
                    userCountDto.setSalesManagerID(0l);
                    break;
                case 3:
                    type=2;
                    userCountDto.setTwoLevelBranchID(infoVo.getOrganizationalID());
                    userCountDto.setSubbranchID(0l);
                    userCountDto.setSalesManagerID(0l);
                    break;
                case 4:
                    type=3;
                    userCountDto.setSubbranchID(infoVo.getOrganizationalID());
                    userCountDto.setSalesManagerID(0l);
                    break;
            }
            CountVo countVo = countMapper.selectCountByConditon(userCountDto);
            ucvv.setoOrUserID(infoVo.getOrganizationalID());
            ucvv.setoOrUserName(infoVo.getOrganizationalName());
            ucvv.setMemberCount(countVo.getMemberCount());
            ucvv.setSalesCount(countVo.getSalesCount());
            ucvv.setUserQty(countVo.getMemberCount()+countVo.getSalesCount());
        }
        List<Long> oIDList = new ArrayList<>();
        Map<String,Object> param = getTransactionByOzOrUserIDList(oIDList, type);
        ucvv.setTransanctionTotal(BigDecimal.ZERO);  //默认给0
        ucvv.setAverageTransanctionTotal(BigDecimal.ZERO); //同上
        BigDecimal total = param.get(ucvv.getoOrUserID().toString())==null ? BigDecimal.ZERO : new BigDecimal(param.get(ucvv.getoOrUserID().toString()).toString());
        ucvv.setTransanctionTotal(total);
        if(ucvv.getUserQty()==0){
            ucvv.setAverageTransanctionTotal(ucvv.getTransanctionTotal());
        }else {
            ucvv.setAverageTransanctionTotal(ucvv.getTransanctionTotal().divide(new BigDecimal(ucvv.getUserQty()),3,BigDecimal.ROUND_HALF_UP));
        }
        return ucvv;
    }

    /**
     * 获取对应IDList的销售额，调用bank服务
     * @param ozOrUserIDList
     * @param type 1分行ID，2二级分行ID，3支行ID，4销售经理ID，5销售顾问ID
     * @return
     */
    private Map<String,Object> getTransactionByOzOrUserIDList(List<Long> ozOrUserIDList,int type){
        Map<String, Object> param = new HashMap<>();
        DataResult result = HttpUtil.httpPost(ProConstants.getTransactionByIDList + type, ozOrUserIDList, restTemplate);
        System.out.print(result.getData());
        if(result.getIsSuccess() == 1) {
            param = (Map<String, Object>) result.getData();
        }else {
            System.out.print("调用bank服务获取对应IDList的销售额失败");
        }
        return param;
    }

    private Count selectByPrimaryKey(Long id){
        Count count = new Count();
        Object object = countMapper.selectByPrimaryKey(id);
        if(object != null){
            count = (Count)object;
        }
        count.setSalesCount(count.getSalesCount()==null ? 0 : count.getSalesCount());
        count.setMemberCount(count.getMemberCount()==null ? 0 : count.getMemberCount());
        return count;
    }

    /**
     * 获取7个时间段/8个时间点
     * @param startTime
     * @param endTime
     * @return
     */
    public Map<Integer,Long> getTimesampInterval(Long startTime,Long endTime){
        Long samp = endTime-startTime;
        if(samp<0){
            throw new ServiceException("时间参数传入有误",RestConst.ErrorCode.SERVICE_FAIL);
        }
        Long a = samp/7; //除以7的整数
        Map<Integer,Long> param = new HashMap<>();
        param.put(1,startTime);
        param.put(2,startTime+a);
        param.put(3,startTime+(2*a));
        param.put(4,startTime+(3*a));
        param.put(5,startTime+(4*a));
        param.put(6,startTime+(5*a));
        param.put(7,startTime+(6*a));
        param.put(8,endTime);
        return param;
    }

    /**
     * 获取需要的时间戳
     * @param type 1昨天零点 2今天零点 3七天前零点 4一月前零点 5三月前零点 6一年前零点
     * @return
     */
    private Long getTimesamp(int type){
        Calendar cal = Calendar.getInstance();
        if(type==1){
            cal.add(Calendar.DATE,-1);
        }
        if(type==2){
        }
        if(type==3){
            cal.add(Calendar.DATE,-7);
        }
        if(type==4){
            cal.add(Calendar.MONTH,-1);
        }
        if(type==5){
            cal.add(Calendar.MONTH,-3);
        }
        if(type==6){
            cal.add(Calendar.YEAR,-1);
        }
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return  cal.getTimeInMillis();
    }
}
